package com.github.yangyishe.p200.p138;

// Definition for a Node.
public class Node {
    public int val;
    public Node next;
    public Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }

    @Override
    public String toString() {
        return "Node{" +
                "val=" + val +
                ", random=" + (random!=null?random.hashCode():null) +
                '}';
    }

    /**
     * 快速构建链表
     * @param arr
     * @return
     */
    public static Node getInstance(Integer[][] arr){
        Node temp=null;
        Node result=null;

        Node[] tempNodes=new Node[arr.length];

        for(int i=0;i<arr.length;i++){
            Node newNode=new Node(arr[i][0]);
            tempNodes[i]=newNode;
            if(temp==null){
                temp=newNode;
                result=newNode;
            }else{
                // 此处递归创建node
                temp.next=newNode;
                temp=newNode;
            }
        }
        for(int i=0;i<arr.length;i++){
            Integer randIndex=arr[i][1];
            if(randIndex!=null){
                tempNodes[i].random=tempNodes[randIndex];
            }
        }


        return result;
    }

    public void print(){
        System.out.println(this);
        if(this.next!=null){
            this.next.print();
        }
    }
}